<template>
  <teleport to="body">
    <transition name="dialog-fade">
      <div class="create-dialog-mask" v-show="showCreateDialog">
        <div class="create-dialog">
          <div class="dialog-header">
            <span>发布新内容</span>
            <button class="close-btn" @click="showCreateDialog = false">×</button>
          </div>
          <div class="dialog-body">
            <label class="form-label">类型：</label>
            <select class="form-select" v-model="createType">
              <option value="post">教学分享</option>
              <option value="qa">问题求助</option>
              <option value="course">课程发布</option>
            </select>

            <label class="form-label">标题：</label>
            <input 
              type="text" 
              class="form-input" 
              v-model="createTitle"
              placeholder="输入标题"
            >

            <label class="form-label">内容：</label>
            <textarea 
              class="form-textarea" 
              v-model="createContent"
              rows="6"
              placeholder="详细描述你的内容"
            ></textarea>

            <label class="form-label">分类：</label>
            <select class="form-select" v-model="createCategory">
              <option 
                v-for="(cat, idx) in createType === 'qa' ? qaCategories : categories" 
                :key="idx"
                :value="cat.id"
              >
                {{ cat.name }}
              </option>
            </select>
          </div>
          <div class="dialog-footer">
            <button class="cancel-btn" @click="showCreateDialog = false">取消</button>
            <button class="confirm-btn" @click="handlePublish">发布</button>
          </div>
        </div>
      </div>
    </transition>
  </teleport>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import axios from 'axios'

const props = defineProps<{
  showCreateDialog: boolean
  categories: Array<{ id: number; name: string }>
  qaCategories: Array<{ id: number; name: string }>
}>()

const emit = defineEmits(['update:showCreateDialog'])

const showCreateDialog = ref(props.showCreateDialog)
const createType = ref<'post' | 'qa' | 'course'>('post')
const createTitle = ref('')
const createContent = ref('')
const createCategory = ref(0)

const handlePublish = async () => {
  if (!createTitle.value || !createContent.value) {
    alert('标题和内容不能为空')
    return
  }

  try {
    await axios.post('/api/create-content', {
      type: createType.value,
      title: createTitle.value,
      content: createContent.value,
      category: createCategory.value
    })
    alert('发布成功')
    showCreateDialog.value = false
    createTitle.value = ''
    createContent.value = ''
    emit('update:showCreateDialog', false)
  } catch (error) {
    console.error('发布失败:', error)
    alert('发布失败，请重试')
  }
}
</script>